<template>
	<view class="main animated fadeIn faster">
		<TitleBarVue :title="title"/>
		<view class="bg-fff rounded30 px-2 pt-3" style="padding-top: 190rpx;">
			<view class="mb-4">
				<view class="d-flex d-flex-middle d-flex-between mb-1">
					<view class="d-flex d-flex-middle d-flex-between" style="width: 100%;">
						<view class="img-bg d-flex d-flex-center d-flex-middle mr-1" style="position: relative;">
							<image @click="touser(record.uid)" :src="record.avatar" class="img-bg-img rounded" mode="aspectFill" style="width: 100rpx; height: 100rpx;"></image>
							<image class="avatar-frame"  src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/dressed/20241031151637-edd9cb3e-ac27-4b3d-929d-aca57a652634.png"></image>
							
						</view>
						<view style="flex: 1;" @click="editParams(record.nickName, null, record.id)">
							<view class="horizontal-container ml-1">
							<view class="mb-1 font30">{{record.nickName}}</view>
							<view class="sex ml-1  " style="width: 30rpx; height: 30rpx; margin-bottom: 25rpx; ">
								<image v-if="record.gender === 1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%94%B7.png" style="width: 100%; height: 100%;"></image>
								<image v-if="record.gender === 2" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203404.png" style="width: 100%; height: 100%;"></image>
							</view>
							</view>
							<view class="font24 color999">{{record.time? record.time : record.gmtCreated}}{{record.ipProvince? ' · '+record.ipProvince.slice(0, 2) : '· 未知'}}</view>
						</view>
						<view @click="concernUser" v-if="record.uid !== this.$store.state.user.uid" class="colorfff mr-2 rounded40 font26" style="background: #45c7ff; padding: 6rpx 15rpx;">{{record.concernFlag? '取关' : '关注'}}</view>
					</view>
				</view>
				<view class="pb-2 ml-1" style="">
					<view class="font26 mb-2">{{record.remark}}</view>
					<view class="topic-list mb-2 d-flex" v-if="record.topicNames">
						<view class="d-flex" v-for="(topic, index) in record.topicNames.split(',')" :key="index">
							<view class="topic-content px-2 py-1">
								 <text class="topic-hash">#</text>
								 <text class="topic-name">{{topic}}</text>
							</view>
						</view>
					</view>
					<view class="mb-2 d-flex">
						<image  v-show="record.screenshot1" 
								:src="record.screenshot1"
								@load="ImgSize($event)"
								@click="previwImage(0)"
								:class="['rounded15',{'MorePic':record.screenshot2&&!record.screenshot3},{'threePic':record.screenshot2&&record.screenshot3}]"
								:mode="record.screenshot2? 'aspectFill' : 'widthFix'" 
								:style="[{maxWidth: record.isLongChart? '550rpx' : '660rpx'}]"
						></image>
						<image  :class="['rounded15', 'ml-1', record.screenshot2&&!record.screenshot3? 'MorePic' : 'threePic']" 
								v-show="record.screenshot2" 
								:src="record.screenshot2" 
								mode="aspectFill"
								@click="previwImage(1)"
						></image>
						<image  :class="['rounded15', 'ml-1', 'mr-2', record.screenshot3? 'threePic' : '']" 
								v-show="record.screenshot3" 
								:src="record.screenshot3" 
								mode="aspectFill"
								@click="previwImage(2)"
						></image>
					</view>
					<!-- <view @click="gotoPromotion" class="aixin rounded30 d-flex d-flex-middle mb-2" style="background: #fcdbf1; display: inline-block; padding: 4rpx 20rpx 6rpx 12rpx;">
						<text class="iconfont icon-aixin_shixin mr" style="color: #FF6C00;"></text>
						<text class="font24">上热门</text>
					</view> -->
				</view>
			</view>
		</view>
		<view class="tab rounded40 ml-2 mb-4" style="background: #cfeffb;" id="comment">{{record.totalCommentCount? record.totalCommentCount : ''}}评论</view>
		
		<view class="pb-10">
			<view class="pl-2 pb-2" v-for="(i, index) in commentList" :key="i.id">
				<view class="d-flex d-flex-middle d-flex-between mb-1">
					<view class="d-flex d-flex-middle d-flex-between" style="width: 100%;">
						<view @click="touser(i.commentUid)" class="img-bg d-flex d-flex-center d-flex-middle mr-1" style="position: relative;">
							<image :src="i.avatar" class="img-bg-img rounded" mode="aspectFill" style="width: 100rpx; height: 100rpx;"></image>
							<image class="avatar-frame"  src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/dressed/20241031151637-edd9cb3e-ac27-4b3d-929d-aca57a652634.png"></image>
							
						</view>
						<view style="flex: 1;" @click="editParams(i.nickname, i.blogId, i.id, index)">
							<view class="horizontal-container ml-1">
							<view class="mb-1 font30">{{i.nickname}}</view>
							<view class="sex ml-1  " style="width: 30rpx; height: 30rpx; margin-bottom: 25rpx; ">
								<image v-if="record.gender === 1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%94%B7.png" style="width: 100%; height: 100%;"></image>
								<image v-if="record.gender === 2" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203404.png" style="width: 100%; height: 100%;"></image>
							</view>
							</view>
							<view class="font24 color999">{{i.time? i.time : i.gmtCreated}}{{i.ipProvince? ' · ' + i.ipProvince.slice(0, 2) : '· 未知'}}</view>
						</view>
						<view class="d-flex">
							<image v-if="!i.favorFlag" @click="changeLikeStatus(index, i.blogId)" class="mr-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%88%B1%E5%BF%83.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<image v-if="i.favorFlag" @click="changeLikeStatus(index, i.blogId)" class="mr-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/heart-3-fill.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<view class="mr-2">{{i.favorCount}}</view>
						</view>
					</view>
				</view>
				<view class="ml-1" style="padding-left: 52px;" @click="editParams(i.nickname, i.blogId, i.id, index)">
					<view class="font26 mb-2 mr-2" style="word-break: break-word;">{{i.commentContent}}</view>
				</view>
				<view class="ml-1" style="padding-left: 52px;">
					<view class="mt-1 d-flex d-flex-middle" v-if="i.hasSub" @click.stop="gotoCommentDetails(i.avatar,i.commentContent,i.gender,i.nickname,i.favorFlag,i.favorCount,i.time,i.id,i.blogId,i.ipProvince,i.commentUid)">
						<view class="font24" style="color: #231816;">展开更多</view>
						<text class="iconfont icon-youjiantou" style="margin-top: 4rpx;"></text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="position-fixed top-0 left-0 right-0" style="bottom: 0; background: transparent;" v-show="focus"></view>

		<view class="d-flex-btn z-index-10 position-fixed w-100 bottom-0 bg-fff py-2":style="{'bottom':keyboardHeight+'px'}">
			<!-- #ifdef APP -->
			<input class="uni-input font26" @input="oninput" @confirm="enterKeyPressed" :focus="focus" @focus="onfocus" @blur="onblur" :placeholder="placeholder" v-model="inputVal" style="flex: 1;"/>
			<!-- #endif -->
			<!-- #ifndef APP -->
			<input class="uni-input font26" :adjust-position="false" @input="oninput" @confirm="enterKeyPressed" :focus="focus" @focus="onfocus" @blur="onblur" :placeholder="placeholder" v-model="inputVal" style="flex: 1;"/>
			<!-- #endif -->
			<text v-show="!focus" class="mx-2 iconfont icon-bianji color6d"></text>
			<view v-show="focus" @click="Comment" class="mx-2 colorfff px-2 py-1 rounded40" :style="{'background': sentBtnStyly}">发送</view>
		</view>
	</view>
</template>

<script>
	import TitleBarVue from '../../components/TitleBar.vue';
	import store from '@/store/index.js';
	import { userApi } from '../../http/userApi';
	import { blogApi } from '../../http/blogApi';
	import { TaskApi } from '../../http/taskApi';
	import loginVue from '../login/login.vue';
	export default {
		data() {
			return {
				title: '动态详情',
				record: [],
				commentList: [],
				images: [],
				keyboardHeight: 0,
				inputVal: "",
				pageIndex: 1,
				pageSize: 10,
				focus: false,
				pageScrollTop: 0,
				placeholder: "友善评论的人都是最可爱哒",
				max: false,
				sentBtnStyly: "rgba(69, 199, 255, .7)",
				params: {
					blogId: null,
					pageIndex: 1,
					pageSize: 10,
				},
				commentParams: {
					blogId: null,
					commentContent: null,
					commentIdRef: null
				},
				commentIndex: null
			}
		},
		components: {TitleBarVue},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			gotoPromotion() {
				uni.navigateTo({
					url: '/pagesApp/Promotion/Promotion'
				})
			},
			// 判断图片尺寸
			ImgSize(event) {
				if(event.detail.width > event.detail.height) { // 横图
					this.record.isLongChart = 0
				}
			},
			// 图片预览
			previwImage(index) {
				if(this.record.screenshot1) {
					this.images.push(this.record.screenshot1)
				}
				if(this.record.screenshot2) {
					this.images.push(this.record.screenshot2)
				}
				if(this.record.screenshot3) {
					this.images.push(this.record.screenshot3)
				}
				uni.previewImage({
					current: index, // 当前显示图片索引
					urls: this.images,// 需要预览的图片http链接列表
				});
				this.images = []
			},
			// 关注
			async concern(params) {
				let res = await userApi.relation(params);
				this.record.concernFlag = !this.record.concernFlag
			},
			
			checkRealNaem(){//判断是否实名
				// if(this.$store.state.user.realName==''||this.$store.state.user.realName==null){
				// 	return false					
				// }else{	
				// 	return true
				// }
				return true
			},
			concernUser() {
				if(this.checkRealNaem()){
				let Params = {
					bindFlag: this.record.concernFlag? 0 : 1,
					fromUid: this.$store.state.user.uid,
					toUid: this.record.uid,
					type: 2
				}
				if(this.record.concernFlag) {
					uni.showModal({
						content: '确定不再关注此人？',
						success: (res) => {
							if (res.confirm) {
								this.concern(Params)
								this.deleteFriend(Params.toUid)
							}
						}
					});
				} else {
					this.concern(Params)
					this.addFriend(Params.toUid)
				}
				}else{
					uni.showModal({
					  content: '你还没有完成实名认证，请先完成实名认证？',
					  confirmText: '去实名',
					  success: (res) => {
					    if (res.confirm) {  
					     uni.navigateTo({
					         url: `/pagesApp/RealName/RealName`
					     });
					    } else if (res.cancel) {
					      // console.log('用户点击取消');
					      // 不执行任何操作，用户取消退出
					    }
					  }
					});
				}	
			},
			// 监测回车按钮
			enterKeyPressed() {
				this.Comment()
			},
			// 评论博客
			async Comment() {
				if(this.checkRealNaem()){
				if(this.inputVal == "") {
					uni.showToast({
						icon: 'none',
						title: '评论不能为空哦',
						duration: 1500
					})
					return
				}
				let res = await blogApi.Comment(this.commentParams)
				if(!this.commentParams.commentIdRef) {
					setTimeout(() => {
						this.FirstComment()
					}, 300)
				} else {
					this.commentList[this.commentIndex].hasSub = true
				}
				this.inputVal = ""
				this.record.totalCommentCount++
				}else{
					uni.showModal({
					  content: '你还没有完成实名认证，请先完成实名认证？',
					  confirmText: '去实名',
					  success: (res) => {
					    if (res.confirm) {  
					     uni.navigateTo({
					         url: `/pagesApp/RealName/RealName`
					     });
					    }
					  }
					});
				}	
			},
			// 修改评论参数
			editParams(nickname, blogId, id, index) {
				if(blogId) {
					this.commentParams.blogId = blogId
					this.commentParams.commentIdRef = id
				} else {
					this.commentParams.blogId = id
					this.commentParams.commentIdRef = null
				}
				if(index != undefined) {
					this.commentIndex = index
				}
				setTimeout(() => {
					this.focus = true
					this.placeholder = "回复 " + nickname + "："
				},300)
			},
			oninput() {
				this.commentParams.commentContent = this.inputVal
				if(this.inputVal != "") {
					this.sentBtnStyly = "rgba(69, 199, 255, 1)"
				} else {
					this.sentBtnStyly = "rgba(69, 199, 255, .7)"
				}
			},
			onfocus() {
				setTimeout(() => {
					this.focus = true
					if(!this.commentParams.commentIdRef) {
						this.placeholder = "回复 " + this.record.nickName + "："
					}
				},300)
			},
			onblur() {
				this.focus = false
				this.placeholder = "友善评论的人都是最可爱哒"
			},
			// 跳转至用户主页
			touser(uid){
				if(uid === this.$store.state.user.uid){
					uni.switchTab({
					    url: '/pages/user/user'
					});
					return
				}
				uni.navigateTo({
				    url: `/pagesMain/HomePage/HomePage?id=${uid}`
				});
			},
			// 查询一级评论
			async LevelOneCommentList() {
				let res = await blogApi.LevelOneComment(this.params)
				if(res.records.length < res.size) {
					this.max = true
				}
				this.commentList = this.commentList.concat(res.records)
			},
			// 查询一级评论(第一条)
			async FirstComment() {
				let params = {
					blogId: this.params.blogId,
					pageIndex: 1,
					pageSize: 1
				}
				let res = await blogApi.LevelOneComment(params)
				this.commentList.unshift(res.records[0]);
				this.getTaskList(20);
			},
			// 评论（点赞 / 取消点赞）
			async changeLikeStatus(index, blogId) {
				this.commentList[index].favorFlag = this.commentList[index].favorFlag? 0 : 1
				if(this.commentList[index].favorFlag) {
					this.commentList[index].favorCount++
				} else {
					this.commentList[index].favorCount--
				}
				let params = {
					toCommentId: this.commentList[index].id,
					flag: this.commentList[index].favorFlag? true : false,
					blogId: blogId
				}
				let res = await blogApi.BlogCommentFavor(params)
			},
			// 添加朋友
			addFriend(uid){
				let that = this
				that.$tim.addFriend({
					to: uid,
					source: 'AddSource_Type_App',
					type: 'Add_Type_Both',
				}).then((imResponse) => {
					const { code } = imResponse.data;
					if (code === 30539) {
					} else if (code === 0) {
						console.log('添加好友成功！')
					}
				}).catch((imError) => {
					console.warn('addFriend error:', imError);
				});
			},
			// 删除好友
			deleteFriend(uid) {
				let that = this
				let userIDList = []
				userIDList.push(uid)
				let promise = that.$tim.deleteFriend({
					userIDList: userIDList,
					type: 'Delete_Type_Both'
				});
				promise.then(function(imResponse) {
					const { successUserIDList, failureUserIDList } = imResponse.data;
					// 删除成功的 userIDList
					successUserIDList.forEach((item) => {
						const { userID } = item;
					});
					// 删除失败的 userIDList
					failureUserIDList.forEach((item) => {
						const { userID, code, message } = item;
					});
					// 如果好友列表有变化，则 SDK 会触发 TencentCloudChat.EVENT.FRIEND_LIST_UPDATED 事件
				}).catch(function(imError) {
					console.warn('removeFromFriendList error:', imError);
				});
			},
			// 跳转至评论详情页
			gotoCommentDetails(avatar,commentContent,gender,nickname,favorFlag,favorCount,time,id,blogId,ipProvince,commentUid) {
				let data = {
					avatar: avatar,
					commentContent: commentContent,
					gender: gender,
					nickname: nickname,
					favorFlag: favorFlag,
					favorCount: favorCount,
					time: time,
					id: id,
					blogId: blogId,
					ipProvince: ipProvince,
					commentUid: commentUid
				}
				uni.navigateTo({
					url: '/pagesMain/CommentDetails/CommentDetails?data='+JSON.stringify(data)
				})
			},
			// 检测键盘高度
			listenKeyboardHeightChange() {
				uni.onKeyboardHeightChange(res => {
					// #ifdef APP
						if(res.height === 0) {
							this.placeholder = "友善评论的人都是最可爱哒"
							this.focus = false
							setTimeout(() => {
								this.commentParams.commentIdRef = null
							},200)
						}
					// #endif
					// #ifndef APP
						this.keyboardHeight = res.height
					// #endif
					
					//#ifdef MP-WEIXIN
						this.keyboardHeight = res.height
						if(res.height === 0) {
							setTimeout(() => {
								this.commentParams.commentIdRef = null
							},200)
						}
					// #endif
				});
			},
			async getTaskList(taskid) {
				let params = {
					id: taskid
				}
				let res = await TaskApi.getTaskList(params)
				if(res.records[0].finishFlag) return
				if(!res.records[0].receiveFlag) {
					this.receiveTask(taskid).then(() => {
						this.finishTask(taskid);
					})
				} else {
					this.finishTask(taskid);
				}
			},
			async receiveTask(id) {
				let params = {
					taskId: id
				}
				let res = await TaskApi.ReceiveTask(params)
				console.log('领取完成！');
			},
			async finishTask(id) {
				let params = {
					taskId: id
				}
				let res = await TaskApi.FinishTask(params);
				console.log('任务完成！');
			}
		},
		// 加载更多
		onReachBottom() {
			if (this.max) {
				return;
			} else {
				this.params.pageIndex++
				this.LevelOneCommentList()
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 300);
		},
		onShow() {
			let	favorData =  uni.getStorageSync('FavorData');
			if(favorData) {
				this.commentList.forEach((item, dex) => {
					if(item.id === favorData.id) {
						this.commentList[dex].favorFlag = favorData.flag
						if(favorData.flag) {
							this.commentList[dex].favorCount++
						} else {
							this.commentList[dex].favorCount--
						}
					}
				})
				uni.removeStorageSync('FavorData');
			}
		},
		// 初始化数据
		onLoad: function(option) {
			this.record = JSON.parse(option.data)
			if(this.record.blogId) {
				this.params.blogId = this.record.blogId
				this.commentParams.blogId = this.record.blogId
			} else {
				this.params.blogId = this.record.id
				this.commentParams.blogId = this.record.id
			}
			this.LevelOneCommentList()
			this.listenKeyboardHeightChange(); // 监听键盘高度变化
		},
		onUnload() {
		    uni.offKeyboardHeightChange(); // 页面卸载时移除键盘高度变化的监听
		}
	}
</script>

<style scoped lang="scss">
	.horizontal-container {
	  display: flex;
	  flex-direction: row;
	  align-items: center; /* 垂直居中 */
	 
	}
	.avatar-frame {
	  position: absolute;
	
	   width: 120rpx; /* 比头像大 20rpx */
	   height: 120rpx; /* 比头像大 20rpx */
	  z-index: 2;  /* 调整层级 */
	  pointer-events: none;
	}
.main {
	background: #fff;
	overflow: hidden;
	.content {
		width: 100%;
		overflow: hidden;
	}
}
.tab {
	background-color: #cfeffb;
	border: 1px solid #7ed1f9;
	color: #57c3fd;
	padding: 12rpx 40rpx;
	display: inline-block;
}
.MorePic {
	width: 200rpx;
	height: 200rpx;
}
.threePic {
	width: 200rpx;
	height: 180rpx;
}
.uni-input {
	margin-left: 20rpx;
	background: #e6f5fb;
	color: #231816;
	border-radius: 50rpx;
	padding-left: 40rpx;
	height: 70rpx;
}
.topic-content {
    display: flex;
    align-items: center;
	border-radius: 30rpx;
	background: #F0F7FF;
	margin-right: 10px;
}
.topic-hash {
    color: #18c3ff;
    font-size: 28rpx;
    margin-right: 3px;
    font-weight: bold;
}
.topic-name {
    font-size: 26rpx;
	color: #999899;
    margin-bottom: 2px;
}
</style>